package l.l.w.leetcode.ZigZagConversion;

import java.util.LinkedList;

/**
 * Created by llw on 2017/8/26.
 */
public class ZigZagConversion {
    /**
     * Z型变换！！！
     * @param s
     * @param numRows
     * @return
     */
    public String convert(String s, int numRows) {
        if(numRows ==1) return s;
        StringBuffer result = new StringBuffer();
        int len = s.length();
        //assert s not null
        for (int i = 0; i < numRows; ++i) {
            int j = 0;
            int k=0;
            int start1,start2;
            start1= i;
            start2= i+2*(numRows - i -1);
            int step = 2*(numRows-1);
            while(true){
                k = start1+step*j;
                if(k >= len)break;
                result.append(s.charAt(k));
                if(i==0 || i == numRows - 1){
                    j++;
                }else{
                    k = start2+step*j++;
                    if(k >= len)break;
                    result.append(s.charAt(k));
                }
            }
        }
        return result.toString();
    }

    /**
     * 按照Z型进行打印！！！
     * @param s
     * @param numRows
     * @return
     */
    public String convert1(String s, int numRows) {
        if(numRows ==1) {
            System.out.println(s);
            return s;
        }
        StringBuffer result = new StringBuffer();
        int len = s.length();
        //assert s not null
        for (int i = 0; i < numRows; ++i) {
            LinkedList<Integer> line = new LinkedList<>();
            int j = 0;
            int k=0;
            int start1,start2;
            start1= i;
            start2= i+2*(numRows - i -1);
            int step = 2*(numRows-1);
            while(true){
                k = start1+step*j;
                if(k >= len)break;
                result.append(s.charAt(k));
                line.add(k);
                if(i==0 || i == numRows - 1){
                    j++;
                }else{
                    k = start2+step*j++;
                    if(k >= len)break;
                    result.append(s.charAt(k));
                    line.add(k);
                }
            }
            int start = line.get(0)-2;
            for(Integer integer:line){
                int num = (integer-start)/2-1;
                for(int h = 0 ; h < num; ++h){
                    System.out.print("  ");
                }
                start = integer;
                System.out.print(s.charAt(integer)+" ");
            }
            System.out.println();

        }
        return result.toString();
    }
    public static void main(String[] args) {
        String a = "PAYPALPAYPALISHIRINGISHIRIPAYPPAYPALISHIRINGALISHIRINGNG";
        String result = new ZigZagConversion().convert1(a, 7);
        System.out.println(result);
    }
}
